import React, {useState, useEffect} from 'react'
import MyHeader from '../../components/header/MyHeader'
import api from '../../api/index'
import style from './style.module.scss'
import { IndexBar, List } from 'antd-mobile'
// import { lorem } from 'demos'

const getRandomList = (min, max) => {
  return new Array(Math.floor(Math.random() * (max - min) + min)).fill('')
}
const charCodeOfA = 'A'.charCodeAt(0)
const groups = Array(26)
  .fill('')
  .map((_, i) => ({
    title: String.fromCharCode(charCodeOfA + i),
    items: [1,2,3].map(()=>123)
  }))

export default function City() {
  // 定义变量存储城市信息
  const [current, setCurrent] = useState('')
  const [hotCity, setHotCity] = useState([])
  const [cityList, setCityList] = useState([])
  // 获取城市列表
  async function getCityList() {
    // TODO: 获取城市列表
    let res = await api.getCity();
    const indexCitys = res.data.city[0];
    // 获取热门城市
    setHotCity(indexCitys.hot)
    // 获取当前城市
    setCurrent(indexCitys.pos[0].name)
    // 获取城市列表
    let groups = [];
    for(let key in indexCitys) {
      if(key === 'hot' || key === 'pos' || indexCitys[key].length === 0){
        continue;
      }else{
        let obj = {};
        obj.title = key;
        // obj.items = indexCitys[key];
        if (Array.isArray(indexCitys[key])) {
          obj.items = indexCitys[key];
        } 
        groups.push(obj);
      }
    }
    setCityList(groups);
  }
  // 生命周期函数
  useEffect(()=>{
    getCityList();
  },[])
  return (
    <div>
      {/* <MyHeader title='城市选择'/> */}
      <MyHeader>城市选择</MyHeader>
      <div className={style.content}>
        {/* 当前城市 */}
        <div className={style.title}>当前城市</div>
        <div className={style.cityname}>{current}</div>
        {/* 热门城市 */}
        <div className={style.title}>热门城市</div>
        <div className={style.citysContent}>
          {
            hotCity.map(ele=>{
              return <div key={ele.id} className={style.cityname}>{ele.name}</div>
            })
          }
        </div>
      </div>
      {/* 城市遍历 */}
      <div className={style.antBox} style={{ height: window.innerHeight-140 }}>
        <IndexBar>
          {cityList.map(group => {
            const { title, items } = group
            return (
              <IndexBar.Panel
                index={title}
                title={`城市${title}`}
                key={`城市${title}`}
              >
                <List>
                  {items.map((item, index) => (
                    <List.Item key={index}>{item.name}</List.Item>
                  ))}
                </List>
              </IndexBar.Panel>
            )
          })}
        </IndexBar>
      </div>
    </div>
  )
}
